<template>
  <div class="avatar-uploader">
    <div tabindex="0" class="el-upload el-upload--text">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <span v-if="imageUrl" class="btn-large-img" @click.stop="isEnlargeimg = true">点击查看大图</span>
      <label class="el-icon-plus avatar-uploader-icon" for="uploadImg"></label>
      <input type="file" accept="image/*" id="uploadImg" ref="selfFile" class="el-upload__input" @change="selfUploadComprss($event)">
    </div>
    <p class="error" v-show="licenseError.status"><i class="el-icon-warning"></i>{{licenseError.text}}</p>
  </div>
</template>

<script>
import {uploadImg} from '@/service/get-data'
export default {
  name: 'certUpload',
  data () {
    return {
      imageUrl: '', // 图片地址
      isEnlargeimg: false, // 显示大小
      licenseError: {status: false, text: '请上传图片'},
      businessLicense: '' // 图片预览地址

    }
  },
  methods: {
    // 自定义上传图片
    selfUploadComprss (e) {
      let _this = this
      var file = this.$refs.selfFile.files[0]
      this.imageUrl = URL.createObjectURL(file)
      this.compress(file, function (ImgBase64) {
        let imgBase64 = ImgBase64 // 存储转换的base64编码
        _this.compressImg = imgBase64 // 显示预览图片
      })
    },
    // 压缩图片
    async compress (fileObj, callback) {
      let _this = this
      try {
        let reader = new FileReader()
        reader.onload = function (e) {
          let image = new Image()
          image.onload = function () {
            let that = this
            let square = 500
            let canvas = document.createElement('canvas')
            let context = canvas.getContext('2d')
            let imageWidth = 0 // 压缩图片的大小
            let imageHeight = 0
            let offsetX = 0
            let offsetY = 0
            let data = ''
            let quality = 0.7
            canvas.width = square
            canvas.height = square
            context.clearRect(0, 0, square, square)
            if (that.width > that.height) {
              imageWidth = Math.round(square * that.width / that.height)
              imageHeight = square
              offsetX = -Math.round((imageWidth - square) / 2)
            } else {
              imageHeight = Math.round(square * this.height / this.width)
              imageWidth = square
              offsetY = -Math.round((imageHeight - square) / 2)
            }
            context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight)
            data = canvas.toDataURL('image/jpeg', quality)
            // 压缩完成执行回调
            callback(data)
            _this.fetchJavaImg(data)
          }
          image.setAttribute('src', e.target.result)
        }
        reader.readAsDataURL(fileObj)
      } catch (e) {
        console.log('压缩失败')
      }
    },
    async fetchJavaImg (dataURI) {
      let param = new FormData() // 创建form对象
      let file = this.dataURItoBlob(dataURI)
      param.append('files', file, 'image.jpeg') // 通过append向form对象添加数据
      let res = await uploadImg(param)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        res = res.data
        this.licenseError.status = false // 隐藏图片
        res.data.map((item, index) => {
          this.businessLicense = item.filePath
        })
      }
    },
    // 上传到后台
    dataURItoBlob (dataURI) {
      var byteString = atob(dataURI.split(',')[1])
      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
      var ab = new ArrayBuffer(byteString.length)
      var ia = new Uint8Array(ab)
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ab], {type: mimeString})
    }
  }
}
</script>

<style lang="scss" scoped>
  .avatar-uploader{
    width: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
